package com.hkccommunity.service.impl;

import com.hkccommunity.entity.Problem;
import com.hkccommunity.mapper.ProblemMapper;
import com.hkccommunity.service.ProblemService;
import com.hkccommunity.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;


public class ProblemServiceImpl implements ProblemService {

    private SqlSessionFactory factory = SqlSessionFactoryUtil.getSqlSessionFactory();

    @Override
    public List<Problem> getProblem(Integer index, Integer num) {
        SqlSession sqlSession = factory.openSession();
        ProblemMapper mapper = sqlSession.getMapper(ProblemMapper.class);
        List<Problem> list = mapper.getProblem(index, num);
        sqlSession.close();
        return list;
    }

    @Override
    public int getCount() {
        SqlSession sqlSession = factory.openSession();
        ProblemMapper mapper = sqlSession.getMapper(ProblemMapper.class);
        int count = mapper.getCount();
        sqlSession.close();
        return count;
    }

    @Override
    public int updateReadCount(Long problemId) {
        SqlSession sqlSession = factory.openSession();
        ProblemMapper mapper = sqlSession.getMapper(ProblemMapper.class);
        int i = mapper.updateReadCount(problemId);
        sqlSession.commit();
        sqlSession.close();
        return i;
    }

    @Override
    public Problem getProblemById(Long problemId) {
        SqlSession sqlSession = factory.openSession();
        ProblemMapper mapper = sqlSession.getMapper(ProblemMapper.class);
        Problem problem = mapper.getProblemById(problemId);
        sqlSession.close();
        return problem;
    }

    @Override
    public int addProblem(Problem problem) {
        SqlSession sqlSession = factory.openSession();
        int i = 0;
        try {
            ProblemMapper mapper = sqlSession.getMapper(ProblemMapper.class);
            i = mapper.addProblem(problem);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return i;
    }

    @Override
    public List<Problem> getProblemByInput( String input) {
        SqlSession sqlSession = factory.openSession();
        ProblemMapper mapper = sqlSession.getMapper(ProblemMapper.class);
        List<Problem> problemByInput = mapper.getProblemByInput( input);
        sqlSession.close();
        return problemByInput;
    }
}
